package com.ks.xcamera.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.ks.basictools.base.BaseActivity;
import com.ks.basictools.manager.ActivityManager;
import com.ks.xcamera.R;
import com.ks.xcamera.manager.ListDataManager;
import com.ks.xcamera.manager.PreferenceManager;
import com.ks.xcamera.manager.UserManager;
import com.ks.xcamera.responseBean.UserResponse;
import com.permissionx.guolindev.PermissionX;

@SuppressLint("CustomSplashScreen")
public class SplashActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBar(true, false, R.color.colorTrans);
        setContentView(R.layout.activity_splash);

        PermissionX.init(this)
                .permissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA
                )
                .explainReasonBeforeRequest()
                .onExplainRequestReason((scope, deniedList) -> scope.showRequestReasonDialog(deniedList, "即将申请的权限是程序必须依赖的权限", "知道了"))
                .onForwardToSettings((scope, deniedList) -> scope.showForwardToSettingsDialog(deniedList, "您需要去应用程序设置当中去手动开启权限", "知道了"))
                .request((allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                        // 开始逻辑
                        start();
                    }
                });
    }

    private void start() {
        boolean login = !TextUtils.isEmpty(PreferenceManager.getInstance().getToken(SplashActivity.this));
        if (login) {
            ListDataManager.getInstance().requestData();
        }
        new Handler().postDelayed(() -> {
            if (!login) {
                startActivity(new Intent(SplashActivity.this, LoginActivity.class));
            } else {
                String json = PreferenceManager.getInstance().getUser(SplashActivity.this);
                UserResponse.UserinfoDTO user = new Gson().fromJson(json, UserResponse.UserinfoDTO.class);
                UserManager.getInstance().saveUser(user);
                startActivity(new Intent(SplashActivity.this, BarCodeActivity.class));
            }
            ActivityManager.getInstance().finishActivity(SplashActivity.class);
        }, 2000);
    }
}